<?php

namespace common\models\dynamic;

use Yii;

/**
 * This is the model class for table "{{%dynamic_like_log}}".
 *
 * @property int $id
 * @property string $dynamic_id 动态ID
 * @property string $user_id 点赞用户UID
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 */
class DynamicLike extends \common\base\ActiveRecord {

    use \common\traits\TimestampBehavior;
    use \common\traits\QueryInstanceActiveRecord;
    use \common\traits\relation\UserData;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%dynamic_like}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['dynamic_id', 'user_id', 'created_at', 'updated_at'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'dynamic_id' => '动态ID',
            'user_id' => '点赞用户UID',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function afterDelete() {
        $model = DynamicStats::findOne([
            'dynamic_id' => $this->dynamic_id,
        ]);
        if ($model) {
            $model->likes -= 1;
            $model->save(false);
        }

        parent::afterDelete();
    }

    public function afterSave($insert, $changedAttributes) {
        $model = DynamicStats::findOrNew([
            'dynamic_id' => $this->dynamic_id,
        ]);
        $model->likes += 1;
        $model->save(false);

        parent::afterSave($insert, $changedAttributes);
    }

}
